package org.nyt.medicalstore.controller;

import org.nyt.medicalstore.model.Drug;
import org.nyt.medicalstore.service.DrugService;
import org.nyt.medicalstore.dto.DrugDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/drugs")
@CrossOrigin(origins = "*")
public class DrugController {
    @Autowired
    private DrugService drugService;

    private DrugDTO toDTO(Drug drug) {
        if (drug == null) return null;
        DrugDTO dto = new DrugDTO();
        dto.setId(drug.getId());
        dto.setName(drug.getName());
        dto.setCode(drug.getCode());
        dto.setSpecification(drug.getSpecification());
        dto.setDosageForm(drug.getDosageForm());
        dto.setManufacturer(drug.getManufacturer());
        dto.setApprovalNumber(drug.getApprovalNumber());
        dto.setPrescription(drug.getPrescription());
        dto.setDescription(drug.getDescription());
        return dto;
    }

    @PostMapping
    public ResponseEntity<?> addDrug(@RequestBody Drug drug) {
        try {
            Drug savedDrug = drugService.saveDrug(drug);
            DrugDTO result = toDTO(savedDrug);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"添加药品失败: " + e.getMessage() + "\"}");
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getDrug(@PathVariable Long id) {
        try {
            Drug drug = drugService.getDrugById(id);
            if (drug == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("{\"error\": \"药品不存在\"}");
            }
            DrugDTO result = toDTO(drug);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"获取药品失败: " + e.getMessage() + "\"}");
        }
    }

    @GetMapping
    public ResponseEntity<?> getAllDrugs() {
        try {
            List<Drug> drugs = drugService.getAllDrugs();
            List<DrugDTO> result = drugs.stream().map(this::toDTO).collect(Collectors.toList());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"获取药品列表失败: " + e.getMessage() + "\"}");
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateDrug(@PathVariable Long id, @RequestBody Drug drug) {
        try {
            Drug existingDrug = drugService.getDrugById(id);
            if (existingDrug == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("{\"error\": \"药品不存在\"}");
            }
            drug.setId(id);
            Drug updatedDrug = drugService.saveDrug(drug);
            DrugDTO result = toDTO(updatedDrug);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"更新药品失败: " + e.getMessage() + "\"}");
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteDrug(@PathVariable Long id) {
        try {
            Drug existingDrug = drugService.getDrugById(id);
            if (existingDrug == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("{\"error\": \"药品不存在\"}");
            }
            drugService.deleteDrug(id);
            return ResponseEntity.ok("{\"message\": \"药品删除成功\"}");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"删除药品失败: " + e.getMessage() + "\"}");
        }
    }
}
